/**  
 * Copyrights@2006, Tianyuan DIC Information Co.,Ltd.
 * 文件名:    TMallPayHandle.java  
 * 描述:   
 * 作者:     kaiyang
 * 版本:    1.0  
 * 创建时间:   2015年5月4日 上午11:57:29  
 *  
 * 修改历史:  
 * 日期                          作者           版本         描述  
 * ------------------------------------------------------------------  
 * 2015年5月4日      kaiyang      1.0        1.0 Version  
 */ 
package com.hp.bon.sgw.wh.channel.handler;

import java.io.IOException;
import java.io.PrintStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.lang.StringEscapeUtils;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.bon.sgw.Constants;
import com.hp.bon.sgw.Constants.MessageType;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.BuzProcessorManager;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.InprogressMessageQueue;
import com.hp.bon.sgw.core.channel.SoapChannel;
import com.hp.bon.sgw.core.channel.handler.IAsynCallHandler;
import com.hp.bon.sgw.domain.MessageDetail;
import com.hp.bon.sgw.start.SpringContext;
import com.hp.bon.sgw.threads.MessageDetailCacheManager;
import com.hp.bon.sgw.threads.TaskManager;
import com.hp.bon.sgw.util.dcc.DccAvpHelper;
import com.hp.bon.sgw.wh.Constants.AliParam;
import com.hp.bon.sgw.wh.Constants.IVRParam;
import com.hp.bon.sgw.wh.bean.Recharge;
import com.hp.bon.sgw.wh.bean.TInterfacePassword;
import com.hp.bon.sgw.wh.bean.tmall.WingBalanceQuery;
import com.hp.bon.sgw.wh.channel.RenewChannel;
import com.hp.bon.sgw.wh.service.TMallResponseService;
import com.hp.bon.sgw.wh.service.TYConfigService;
import com.hp.bon.sgw.wh.service.TmallLogDao;
import com.hp.bon.sgw.wh.utils.ThreeDESKeyParam;
import com.hp.ocs.diameter.message.AVP;
import com.hp.ocs.diameter.message.AVP_Grouped;
import com.hp.ocs.diameter.message.AVP_Integer32;
import com.hp.ocs.diameter.message.AVP_UTF8String;
import com.hp.ocs.diameter.message.Message;

import freemarker.template.Template;

/**  
 * @ClassName: TMallPayHandle   
 * @Description: TODO  
 * @author: kaiyang  
 * @date:2015年5月4日 上午11:57:29     
 */
public class QryHandle  implements IAsynCallHandler{
	private static final Logger logger = LoggerFactory.getLogger(RenewChannel.class);
	private PrintStream printStream;
	private String appCode;
	private String ips;
	private String version;
    private Template template1 = null;
	private TYConfigService tyConfigService;
    public static String temp="";
    public static String validMark="";
    private  XmlMessage reqXmlMessage;
    public  String validBalances;
    public  String queryFlags;
    public  String password="";
    public  String url="";
    public  WingBalanceQuery wingBalanceQuery;
    public  Map<String, Recharge> rechargeMap= new HashMap<String, Recharge>();
	public Recharge recharge= new Recharge();
	public QryHandle(PrintStream printStream,String queryFlags,String password,String url,WingBalanceQuery wingBalanceQuery,XmlMessage reqXmlMessage,String appCode,String ips,String version)
	{
		logger.info("==========QryHandle(PrintStream printStream)===== ");
		this.printStream = printStream;
		this.appCode = appCode;
		this.ips = ips;
		this.version = version;
		this.queryFlags = queryFlags;
		this.tyConfigService=tyConfigService;
		this.password = password;
		this.reqXmlMessage = reqXmlMessage;
		this.url = url;
		this.wingBalanceQuery =	wingBalanceQuery;
	}
	
	@Override
	public int getProtocolType() {
		return 0;
	}
  
	@Override
	public void onCallResult(CallParam callParam) {
		logger.info("===========QryHandle=onCallResult==== ");
		long receiveTime = System.currentTimeMillis();
		XmlMessage ack = null;
		Object response = null;
		if (callParam.getResponse() != null) {
			response = callParam.getResponse();
		} else if (callParam.getRecvResponse() != null) {
			response = callParam.getRecvResponse();
		}
		
		if (response == null) {
			logger.info("QryHandleresponse == null");
			ack = SoapChannel.createERRAnwser(
					callParam.getSessionId(),
					callParam.getRetCode() == 3002 ? 11202 : callParam
							.getRetCode(), callParam.getResultMsg());
		} else {
			logger.info("QryHandleleresponse:feikong");	
			if (response instanceof Message) {// CCA -> XML
				logger.warn("QryHandleHandleCCA -> XML");	
				ack = BuzProcessorManager.getInstance().convertMessageToAck(
						callParam);
			} else if (response instanceof XmlMessage) {
				logger.info("QryHandleleresponse instanceof XmlMessage");	
				ack = (XmlMessage) response;
			} else {
				logger.info("QryHandleHandleunknown response type:"
						+ callParam.getResponse().getClass().getName());
			}
		}
		try {
			logger.info("============QryHandleHandleconvertResponseString之前============= ");
			String respXML = convertResponseString((Message)response,callParam.getServiceResultCode(),callParam.getSessionId());
			byte[] resp = respXML.getBytes("GBK");
			logger.info("============QryHandleHandlerespXMLqqqsaaa============= " + respXML);
			logger.info("============QryHandleHandlerespqueryFlags============ " + queryFlags);
			logger.info("============QryHandlvalidMark=========== " + validMark);
			if(!temp.equals("0")&&!temp.equals("")){
				logger.info("==========temp判断============"+temp+"==");
				Element serviceInformationRecharge = DocumentHelper
						.createElement("Service_Information");
				Element elementRe = serviceInformationRecharge
						.addElement("Result");
				elementRe.setText(temp);
				temp="";
				elementRe = serviceInformationRecharge.addElement("RESPONSECODE");
				elementRe.setText("");
				elementRe = serviceInformationRecharge.addElement("RESPONSECONTENT");
				elementRe.setText("");
				elementRe = serviceInformationRecharge.addElement("CURRDATE");
				elementRe.setText("");
				elementRe = serviceInformationRecharge.addElement("BESTPAYBALANCE");
				elementRe.setText("");
				elementRe = serviceInformationRecharge.addElement("TELBALANCE");
				elementRe.setText("");
				elementRe = serviceInformationRecharge.addElement("TOTALBALANCE");
				elementRe.setText("");
				elementRe = serviceInformationRecharge.addElement("ISBESTPAYACCT");
				elementRe.setText("");
				
//				recharge.setMark("1");
//				AliParam.setTemp("1");//失败或者异常
//				rechargeMap.put(callParam.getSessionId(), recharge);
//				AliParam.setRechargeMap(rechargeMap);
				XmlMessage ack1 = new XmlMessage(true);
				ack1.setMID(callParam.getSessionId());
				ack1.setREPTAG(0);
				ack1.setRTT(String.valueOf(receiveTime));
				ack1.setSIG(null);
				ack1.setRC("0");
				ack1.setDS("SUCCESS");
				ack1.setDATA(serviceInformationRecharge.asXML());
				String respXMLa = convertResponseString(ack1);
				logger.info(respXMLa);
				byte[] resps = respXMLa.getBytes("UTF-8");
				ack1.setLength(resps.length);
				ack1.setMsgTime(System.currentTimeMillis());
				printStream.write(resps);
				printStream.close();
			}else	if(validMark.equals("1")&&queryFlags.equals("1")){
				validMark="";
				queryFlags="";
				TmallLogDao tmallLogDao=(TmallLogDao)SpringContext.getInstance().getApplicationContext().getBean("tmallLogDao");
				TInterfacePassword tInterfacePassword = tmallLogDao.getTInterfacePassword();
				logger.info("============QryHandleHtInterfacePassword.getKeyValue()========== " + tInterfacePassword.getKeyValue());
				try {
					logger.info("============QryHandlvalidMark=========== " + validBalances);
					logger.info("=========appCode======== " + appCode);
					logger.info("=========ips======== " + ips);
					logger.info("=========version======== " + version);
					getBalanceQuery(tInterfacePassword.getKeyValue(), "", url, wingBalanceQuery, reqXmlMessage, printStream, receiveTime,validBalances,appCode,ips,version);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
//				Element serviceInformationBa = DocumentHelper
//						.createElement("Service_Information");
//				Element elementRe = serviceInformationBa
//						.addElement("Result");
//				elementRe.setText("0");
//				elementRe = serviceInformationBa.addElement("RESPONSECODE");
//				elementRe.setText("");
//				elementRe = serviceInformationBa.addElement("RESPONSECONTENT");
//				elementRe.setText("");
//				elementRe = serviceInformationBa.addElement("CURRDATE");
//				elementRe.setText("");
//				elementRe = serviceInformationBa.addElement("BESTPAYBALANCE");
//				elementRe.setText("");
//				elementRe = serviceInformationBa.addElement("TELBALANCE");
//				elementRe.setText(validBalances);
//				elementRe = serviceInformationBa.addElement("TOTALBALANCE");
//				elementRe.setText(validBalances);
//				elementRe = serviceInformationBa.addElement("ISBESTPAYACCT");
//				elementRe.setText("FALSE");
//				
//				logger.info("===========QryHandleHandle=etst============= " + callParam.getSessionId());
//				XmlMessage ack1 = new XmlMessage(true);
//				ack1.setMID(callParam.getSessionId());
//				ack1.setREPTAG(0);
//				ack1.setRTT(String.valueOf(receiveTime));
//				ack1.setSIG(null);
//				ack1.setRC("0");
//				ack1.setDS("SUCCESS");
//				ack1.setDATA(serviceInformationBa.asXML());
//				String respXMLa = convertResponseString(ack1);
//				logger.info("=============QryHandle==========serviceInformationRecharge========================"+ack1.getDATA());
//				logger.info(respXMLa);
//				logger.info("=============QryHandle==========serviceInformationRecharge========================");
//				byte[] resps = respXMLa.getBytes("UTF-8");
//				logger.info("============QryHandle====as========= " + respXMLa);
//				ack1.setLength(resps.length);
//				ack1.setMsgTime(System.currentTimeMillis());
//				printStream.write(resps);
//				printStream.close();
			}
			
		
		

			callParam.setResponse(ack);

			if (callParam.getRetCode() == Constants.ResultCode.SUCCESS) {// 成功的消息，请求应答入库
				logger.info("callParam.getRetCode() ==" + callParam.getRetCode());
				MessageDetail detail = new MessageDetail();
				detail.setBusinessCallId(callParam.getBussinessCallId());
				logger.info("callParam.getBussinessCallId()== " + callParam.getBussinessCallId());
				detail.setSessionId(callParam.getSessionId());
				logger.info("callParam.getSessionId() ==" + callParam.getSessionId());
				detail.setServiceContextId(callParam.getServiceContextId());
				logger.info("callParam.getServiceContextId() ==" + callParam.getServiceContextId());
				detail.setMessageType(MessageType.WSA);
				detail.setDetails(ack.getDATA());
				logger.info("ack.getDATA()== " + ack.getDATA());
				detail.setMsgTime(new Date(ack.getMsgTime()));
				detail.setOpType("send");
				detail.setHostId(callParam.getUserName());
				MessageDetailCacheManager.getInstance().add(detail);
			}
			TaskManager.taskProcess(callParam);
			logger.info("http response(Recharge)aa " + respXML);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private String convertResponseString(Message answer, int serviceResultCode,String sessionId)
	{
		
		logger.info("===============QryHandle=进入convertResponseString========");
		logger.info("===========QryHandle=====serviceResultCode========"+serviceResultCode);
		String response = "";	    	
		Map<String,String> data = new HashMap<String, String>();
	
		 if (serviceResultCode == 0)   
		{
			try{
			    //service_infomation
			    AVP avp = answer.find(Constants.DIAMETER_AVP_SERVICE_INFOMATION,Constants.DIAMETER_VENDOR_3GPP);
			    AVP_Grouped avpServiceInfomation = new AVP_Grouped(avp);
			    //Bill_Serial_Nbr
//			    AVP queryFlagAvp = avpServiceInfomation.find(5087,Constants.DIAMETER_VENDOR_CT);
//			    logger.info("===============QryHandle=判断queryFlagAvp========");
//			    if (queryFlagAvp != null){
//			    	logger.info("===============QryHandle=判断queryFlagAvp========");
//			    	int  queryFlag= new AVP_Integer32(queryFlagAvp).queryValue();
//			    	queryFlags=String.valueOf(queryFlag);
//			    	AliParam.setQueryFlag(String.valueOf(queryFlag));
//			      logger.info("===============QryHandle========"+queryFlag);
//			    	data.put("queryFlag",String.valueOf(queryFlag));
//			    }
			    AVP validBalanceAvp = avpServiceInfomation.find(80118,Constants.DIAMETER_VENDOR_CT);
			    if (validBalanceAvp != null){
				    	logger.info("============QryHandle====(validBalance != null)========");
//				    	queryFlag = new AVP_UTF8String(queryFlagAvp).queryValue();
				    	int  validBalance= new AVP_Integer32(validBalanceAvp).queryValue();
				    	validMark="1";
				    	validBalances=String.valueOf(validBalance);
				     	logger.info("============QryHandle====validBalances======"+validBalances);
//				    	AliParam.setValidBalance(String.valueOf(validBalance));
				    }
			    
			    logger.info("============QryHandletttttttttttttttttttt========");
				String sessionId1 = AVP_UTF8String.queryValue(answer.find(Constants.DIAMETER_AVP_SESSION_ID));
				logger.info("============QryHandlettttttttteeeeeeeeeeeeeeeeee========"+sessionId1);
				String uniqueID = DccAvpHelper.getMessageUniqueID(sessionId1.substring(0,sessionId1.length()-1), answer);
				logger.info("==========QryHandlelllllllllllllllllllllllllll========"+uniqueID);
				CallParam callParam =  InprogressMessageQueue.getInstance().removeProgress(sessionId1.substring(0,sessionId1.length()-1));
				callParam =  InprogressMessageQueue.getInstance().removeProgress(sessionId1);
			}catch(Exception e){
//				data.put("coopOrderNo","");
//				data.put("coopOrderStatus",TMallChannel.STATUS_FAIL);
//				data.put("coopOrderSnap","ReCharge");
//				data.put("coopOrderSuccessTime","");
//				data.put("failedCode","0503");
//				data.put("failedReason","");
				e.printStackTrace();
			}
//			data.put("coopOrderNo",billSerialNbr);
//			data.put("coopOrderStatus",TMallChannel.STATUS_SUCCESS);
//			data.put("coopOrderSnap","ReCharge");
//			data.put("coopOrderSuccessTime",operTime);
//			data.put("failedCode", "");
//			data.put("failedReason","");
		}
		else   //充值失败
		{
			 logger.info("设置异常1"+serviceResultCode);
			temp=String.valueOf(serviceResultCode);
			 logger.info("设置异常2"+serviceResultCode);
//			recharge.setServiceResultCode(String.valueOf(serviceResultCode));
		
		}
//		TreeMap<String,String> paraMap = new TreeMap<String, String>();
//		String coopOrderNo = data.get("coopOrderNo");
//		String status = data.get("coopOrderStatus"); 
//		paraMap.put("coopOrderNo", coopOrderNo);
//		paraMap.put("coopOrderStatus", status);
//		if (status != null && (status.equals(TMallChannel.STATUS_SUCCESS)||status.equals(TMallChannel.CANCEL)||status.equals(TMallChannel.STATUS_FAIL)))
//		{
//			if (status.equals(TMallChannel.STATUS_SUCCESS))
//			{
//				String coopOrderSnap = data.get("coopOrderSnap");
//				String coopOrderSuccessTime = data.get("coopOrderSuccessTime");
//				paraMap.put("coopOrderSnap", coopOrderSnap);
//				paraMap.put("coopOrderSuccessTime", coopOrderSuccessTime);
//			}
//			else if (status.equals(TMallChannel.CANCEL) || status.equals(TMallChannel.STATUS_FAIL))
//			{
//				String failedCode = data.get("failedCode");
//				paraMap.put("failedCode",failedCode);
//				paraMap.put("failedReason", failedCode);
//			}
//			String source = "";
//			for(Entry<String,String> entry:paraMap.entrySet())
//			{
//				source += entry.getKey()+entry.getValue();
//			}
//			String sign = SignUtilsImpl.getTmallSign(source);
//			paraMap.put("sign",sign);
//		}
		
	
		response = getResponse1(data);;
		return response;
	}
	
	
	public void getBalanceQuery(String key, String acceptOrgCode, String url,
			WingBalanceQuery wingBalanceQuery, XmlMessage reqXmlMessage,
			PrintStream body, long receiveTime,String ValidBalance,String appCode,String ips,String version ) throws Exception {
		
		logger.info("key========" + key);
		logger.info("acceptOrgCode========" + acceptOrgCode);
		logger.info("url========" + url);
		logger.info("reqXmlMessage========" + reqXmlMessage.getDATA());
		logger.info("receiveTime========" + receiveTime);
		logger.info("ValidBalance========" + ValidBalance);
		logger.info("appCode==2======" + appCode);
		logger.info("ips=====2===" + ips);
		logger.info("version=2=======" + version);
		StringBuffer params = new StringBuffer();
		params.append("{\"PARAMS\":{");
		params.append("\"ACCOUNTIDTYPE\":");
		params.append("\"" + wingBalanceQuery.getAccountidtype() + "\",");
		params.append("\"QUERYTYPE\":");
		params.append("\"" + wingBalanceQuery.getQuerytype() + "\",");
		
		logger.info("wingBalanceQuery.getAcceptchannel()========" + wingBalanceQuery.getAcceptchannel());
		if (wingBalanceQuery.getAcceptchannel() != null
				&& !"".equals(wingBalanceQuery.getAcceptchannel())) {
			params.append("\"ACCEPTCHANNEL\":");
			params.append("\"" + wingBalanceQuery.getAcceptchannel() + "\",");
		}
		params.append("\"ACCEPTSEQNO\":");
		params.append("\"" + wingBalanceQuery.getAcceptseqno() + "\",");
		logger.info("wingBalanceQuery.getAccepttime()========" + wingBalanceQuery.getAccepttime());
		if (wingBalanceQuery.getAccepttime() != null
				&& !"".equals(wingBalanceQuery.getAccepttime())) {
			params.append("\"ACCEPTTIME\":");
			params.append("\"" + wingBalanceQuery.getAccepttime() + "\",");
		}
		logger.info("wingBalanceQuery.getAccountid()========" + wingBalanceQuery.getAccountid());
		params.append("\"ACCOUNTID\":");
		params.append("\"" + wingBalanceQuery.getAccountid() + "\"}");
		
		params.append(",\"APP_CODE\":\""
				+ appCode + "\",\"IP\":\""
				+ ips
				+ "\",\"SERVICE_CODE\":\"P30160\",\"VERSION\":\""
				+ version + "\"}");

		logger.info("======获取交易密钥=======发送给集团的字符串=" + params.toString());

		ThreeDESKeyParam des = ThreeDESKeyParam.getInstance();
		String strEnc = des.getEncString(params.toString(), key);

		String json = "{\"REQ_HEAD\":{\"ACCEPTORGCODE\":\""+wingBalanceQuery.getAcceptorgcode()+"\"},\"REQ_BODY\":{\"ENCRYPTSTR\":\""
				+ strEnc + "\"}}";

		logger.info("======获取交易密钥=======发送给集团包含密文的字符串=" + json);

		String reqText = postHttpReq(json, url);
//		reqText = new String(reqText.getBytes("ISO8859-1"), "UTF-8");	
		logger.info("======获取交易密钥=======集团返回的包含密文的字符串=" + reqText);

		JSONObject jsonObject = JSONObject.fromObject(reqText);
		String repHead = jsonObject.getString("RSP_HEAD");
		logger.info("======获取交易密钥返回的消息RSP_HEAD=" + repHead);

		JSONObject jsonRepHead = JSONObject.fromObject(repHead);
		String responSecode = jsonRepHead.getString("RESPONSECODE");
		logger.info("======获取交易密钥返回的消息RESPONSECODE=" + responSecode);

		String responSecontent = jsonRepHead.getString("RESPONSECONTENT");
		logger.info("======获取交易密钥返回的消息RESPONSECONTENT=" + responSecontent);
		

		Element serviceInformation = DocumentHelper.createElement("Service_Information");
		
		Element element = serviceInformation.addElement("Result");
		if (responSecode.equals("000000")) {
			element.setText("0");
			
			String rspBody = jsonObject.getString("RSP_BODY");
			logger.info("=====获取交易密钥返回的消息，需要解密的RSP_BODY=" + rspBody);
			JSONObject jsonRspBody = JSONObject.fromObject(rspBody);
			String encryptStr = jsonRspBody.getString("ENCRYPTSTR");
			logger.info("=====获取交易密钥返回的消息，需要解密的串ENCRYPTSTR=" + encryptStr);

			String strDes = des.getDesString(encryptStr, key);
			logger.info("=====获取解密后的字符串=" + strDes);
			jsonObject = JSONObject.fromObject(strDes);

			String currdate = jsonObject.getString("CURRDATE");
			String bestpaybalance = jsonObject.getString("BESTPAYBALANCE");
			String telbalance = jsonObject.getString("TELBALANCE");
			String totalbalance = jsonObject.getString("TOTALBALANCE");
			String isbestpayacct = jsonObject.getString("ISBESTPAYACCT");
			
			
			element = serviceInformation.addElement("CURRDATE");
			if (currdate.isEmpty() || currdate.equals("")) {
				element.setText("");
			} else {
				element.setText(currdate);
			}
			element = serviceInformation.addElement("BESTPAYBALANCE");
			if (bestpaybalance.isEmpty() || bestpaybalance.equals("")) {
				element.setText("");
			} else {
				element.setText(bestpaybalance);
			}
			element = serviceInformation.addElement("TELBALANCE");
			logger.info("=====telbalance=" + telbalance);
			logger.info("=====bestpaybalance=" + bestpaybalance);
			logger.info("=====ValidBalance=" + ValidBalance);
//			if (telbalance.isEmpty() || telbalance.equals("")) {
//				element.setText("");
//			} else {
				element.setText(ValidBalance);
//			}
			element = serviceInformation.addElement("TOTALBALANCE");
			if (bestpaybalance.isEmpty() || bestpaybalance.equals("")) {
				element.setText(String.valueOf(Integer.parseInt(ValidBalance)));
			} else {
				element.setText(String.valueOf(Integer.parseInt(bestpaybalance)+Integer.parseInt(ValidBalance)));
			}
			element = serviceInformation.addElement("ISBESTPAYACCT");
			if (isbestpayacct.isEmpty() || isbestpayacct.equals("")) {
				element.setText("");
			} else {
				element.setText("TRUE");
			}
			
		} else {
			element.setText("-1");
		}
		
		element = serviceInformation.addElement("RESPONSECODE");
		if (responSecode.isEmpty() || responSecode.equals("")) {
			element.setText("");
		} else {
			element.setText(responSecode);
		}
		element = serviceInformation.addElement("RESPONSECONTENT");
		if (responSecontent.isEmpty() || responSecontent.equals("")) {
			element.setText("");
		} else {
			element.setText(responSecontent);
		}

		XmlMessage ack = new XmlMessage(true);
		ack.setMID(reqXmlMessage.getMID());
		ack.setREPTAG(0);
		ack.setRTT(String.valueOf(receiveTime));
		ack.setSIG(null);
		ack.setRC("0");
		ack.setDS("SUCCESS");
		ack.setDATA(serviceInformation.asXML());
		String respXML = convertResponseString(ack);
		logger.info("=======================respXML========================");
		logger.info(respXML);
		logger.info("=======================respXML========================");
		byte[] resps = respXML.getBytes("UTF-8");
		ack.setLength(resps.length);
		ack.setMsgTime(System.currentTimeMillis());
		body.write(resps);
		body.close();
	}
	
	
	public static String postHttpReq(String json, String url) {
		HttpClient httpClient = new HttpClient();

		byte b[] = json.getBytes();// 把字符串转换为二进制数据
		RequestEntity requestEntity = new ByteArrayRequestEntity(b);

		EntityEnclosingMethod postMethod = new PostMethod();
		postMethod.setRequestEntity(requestEntity);// 设置数据
		postMethod.setPath(url);// 设置服务的url
		// postMethod.setRequestHeader("Content-Type",
		// "application/soap+xml; charset=UTF-8");// 设置请求头编码
		httpClient.getParams().setContentCharset("UTF-8");
		// 设置连接超时
		httpClient.getHttpConnectionManager().getParams()
				.setConnectionTimeout(5 * 1000);
		// 设置读取超时
		httpClient.getHttpConnectionManager().getParams()
				.setSoTimeout(20 * 1000);
		httpClient.getHttpConnectionManager().getParams()
				.setSoTimeout(60 * 1000);

		String responseMsg = "";
		int statusCode = 0;
		try {
			statusCode = httpClient.executeMethod(postMethod);// 发送请求
			responseMsg = postMethod.getResponseBodyAsString();// 获取返回值
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			postMethod.releaseConnection();// 释放连接
		}

		if (statusCode != HttpStatus.SC_OK) {
			System.out.println("HTTP服务异常" + statusCode);
		}
		return responseMsg;
	}
	public String getResponse1(Map<String, String> data)
	{
	    String context = "";
	    if (template1 != null)
	    {
	      StringWriter writer = new StringWriter();
	      try {
	        template1.process(data, writer);
	      } catch (Exception e) {
	    	  logger.error("TMallResponseService getResponse error, msg = {}", e.getMessage());
	        e.printStackTrace();
	      }
	      context = writer.toString();
	    }
	    logger.info("response = {}",context);
	    return context;
	   
	}
	protected String convertResponseString(XmlMessage ack) {
		String orinData = ack.getDATA();
		String dataStr = (orinData == null || orinData.isEmpty()) ? orinData
				: "<![CDATA[" + orinData + "]]>";
		String errMsg = ack.getDS();
		errMsg = (errMsg != null) && (errMsg.indexOf('&') == -1)
				&& (errMsg.indexOf('>') == -1) && (errMsg.indexOf('<') == -1) ? errMsg
				: StringEscapeUtils.escapeXml(errMsg);
		// String respXML__ =
		// "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Header/><SOAP-ENV:Body><ns3:SgwQueryAck xmlns:ns3=\"http://www.chinatelecom.cn/SGW/SOAP\"><MID>"
		// + ack.getMID() + "</MID><REPTAG>0</REPTAG><RTT>" + ack.getRTT() +
		// "</RTT><SIG>"
		// + ack.getSIG() + "</SIG><RC>" + ack.getRC() + "</RC><DS>" + errMsg +
		// "</DS><DATA>" + dataStr +
		// "</DATA></ns3:SgwQueryAck></SOAP-ENV:Body></SOAP-ENV:Envelope>";
		StringBuilder respXML = new StringBuilder();
		respXML.append("<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Header/><SOAP-ENV:Body><ns3:SgwQueryAck xmlns:ns3=\"http://www.chinatelecom.cn/SGW/SOAP\"><MID>");
		respXML.append(ack.getMID());
		respXML.append("</MID><REPTAG>0</REPTAG><RTT>");
		respXML.append(ack.getRTT());
		respXML.append("</RTT><SIG>");
		respXML.append(ack.getSIG());
		respXML.append("</SIG><RC>");
		respXML.append(ack.getRC());
		respXML.append("</RC><DS>");
		respXML.append(errMsg);
		respXML.append("</DS>");
		// //增加unified info
		// if(ack instanceof UnifiedXmlMessage && ack.isUnified()){
		// UnifiedXmlMessage uxmlMsg = (UnifiedXmlMessage)ack;
		// if(!uxmlMsg.getInfoElements().isEmpty()){
		// respXML.append("<INFO>");
		// for(Element infoEle : uxmlMsg.getInfoElements()){
		// String infoData = infoEle.asXML();
		// respXML.append("<![CDATA[");
		// respXML.append(infoData);
		// respXML.append("]]>");
		// }
		// respXML.append("</INFO>");
		// }
		// }
		//
		// //新SOAP请求的新报文转化为老SR、DCC成功后，返回的新SOAP ACK内加入三个AVP组 XML信息
		// if(ack.getInfo()!=null&&!"".equals(ack.getInfo())){
		// respXML.append(ack.getInfo());
		// }
		respXML.append("<DATA>");
		respXML.append(dataStr);
		respXML.append("</DATA></ns3:SgwQueryAck></SOAP-ENV:Body></SOAP-ENV:Envelope>");
		return respXML.toString();
	}
	
}
